// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.security;

import lichen.security.Secured;
import lichen.security.SecurityChecker;

import org.apache.tapestry5.model.MutableComponentModel;
import org.apache.tapestry5.services.ClassTransformation;
import org.apache.tapestry5.services.ComponentClassTransformWorker;
import org.apache.tapestry5.services.TransformConstants;

/**
 * 对安全角色的增强器.
 * @author Jun Tsai
 * @version $Revision: 225 $
 * @since 0.0.3
 */
public class SecurityWorker implements ComponentClassTransformWorker{

	private SecurityChecker _checker;
	public SecurityWorker(SecurityChecker checker){
		this._checker= checker;
	}
	/**
	 * 
	 * @see org.apache.tapestry5.services.ComponentClassTransformWorker#transform(org.apache.tapestry5.services.ClassTransformation, org.apache.tapestry5.model.MutableComponentModel)
	 * @since 0.0.3
	 */
	public void transform(ClassTransformation transformation, MutableComponentModel model) {
		//对类的安全注释进行检查.
		Secured annotation = transformation.getAnnotation(Secured.class);
		
        if (annotation == null)
            return;
        String checker=transformation.addInjectedField(SecurityChecker.class, "_$checker", _checker);
        String pageSecurity=transformation.addInjectedField(Secured.class, "_$page_security", annotation);
        
//      Extend class
        transformation.extendMethod(
                TransformConstants.BEGIN_RENDER_SIGNATURE,String.format("%s.check(%s);",checker,pageSecurity));
        transformation.extendMethod(
                TransformConstants.CLEANUP_RENDER_SIGNATURE,"System.out.println(\"end secured\");");
		
	}

}
